// https://leetcode.cn/problems/largest-divisible-subset/
// Created by ade on 2022/11/9.
// 给你一个由 无重复 正整数组成的集合 nums ，请你找出并返回其中最大的整除子集 answer ，子集中每一元素对 (answer[i], answer[j]) 都应当满足：
//answer[i] % answer[j] == 0 ，或
//answer[j] % answer[i] == 0
//如果存在多个有效解子集，返回其中任何一个均可。
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int> &nums) {
        /*int len = nums.size();
        sort(nums.begin(), nums.end());

        // 第 1 步：动态规划找出最大子集的个数、最大子集中的最大整数
        // 2, 4, 7, 8, 9, 12, 16, 20
        // 1  2	 1	3  1  3	  4	  3
        vector<int> dp(len, 1);
        int maxSize = 1;
        int maxVal = dp[0];
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < i; j++) {
                // 题目中说「没有重复元素」很重要
                if (nums[i] % nums[j] == 0) {
                    dp[i] = max(dp[i], dp[j] + 1);
                }
            }

            if (dp[i] > maxSize) {
                maxSize = dp[i];
                maxVal = nums[i];
            }
        }

        // 第 2 步：倒推获得最大子集
        vector<int> res;
        if (maxSize == 1) {
            res.push_back(nums[0]);
            return res;
        }

        for (int i = len - 1; i >= 0 && maxSize > 0; i--) {
            if (dp[i] == maxSize && maxVal % nums[i] == 0) {
                res.push_back(nums[i]);
                maxVal = nums[i];
                maxSize--;
            }
        }
        return res;*/
        sort(nums.begin(), nums.end());
        int len = nums.size();
        vector<int> dp(len, 1);
        int maxVal = nums[0], maxSize = 1;
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0) {
                    dp[i] = max(dp[i], dp[j] + 1);
                }
            }
            if (dp[i] > maxSize) {
                maxVal = nums[i];
                maxSize = dp[i];
            }
        }
        if (maxSize == 1) return {nums[0]};
        vector<int> res = {};
        for (int i = len - 1; i >= 0; i--) {
            if (maxVal % nums[i] == 0 && maxSize == dp[i]) {
                res.push_back(nums[i]);
                maxVal = nums[i];
                maxSize--;
            }
        }
        return res;
    }
};

int main() {
    Solution so;
    vector<int> nums = {2, 4, 7, 8, 9, 12, 16, 20};

}